package com.tjbklx1.thread.chap05.demo01;

public class Table {

	private final String[] buffer;
	private int tail;
	private int head;
	private int count;

	public Table(int count) {
		this.buffer = new String[count];
		this.head = 0;
		this.tail = 0;
		this.count = 0;
	}

	public synchronized void put(String cake) throws InterruptedException {
		while (count >= buffer.length) {
			System.out.println("producer put fail");
			wait();
		}
		buffer[tail] = cake;
		tail = (tail + 1) % buffer.length;
		count++;
		System.out.println(Thread.currentThread().getName() + " puts " + cake + ", Cake size =" + (count + 1));
		notifyAll();
	}

	public synchronized String take() throws InterruptedException {
		while (count < 0) {
			System.out.println("comsumer take fail");
			wait();
		}
		String cake = buffer[head];
		head = (head + 1) % buffer.length;
		count--;
		System.out.println(Thread.currentThread().getName() + " takes " + cake + ", Cake size =" + (count + 1));
		notifyAll();
		return cake;
	}
}
